<template>
	<view class="store-booking">
		<!-- 导航栏 -->
		<nav-bar title="门店预约"></nav-bar>
		<!-- 未选择提示 -->
		<view class="unselected-tips" v-if="showUnselectedTips">
			<view class="tips-item" v-if="selectedStoreIndex === null" @tap="scrollToStore">
				<text class="icon">●</text>
				<text>选择门店</text>
				<text class="jump-text">点击跳转</text>
			</view>
			<view class="tips-item" v-if="!selectedTechId" @tap="scrollToTechnician">
				<text class="icon">●</text>
				<text>选择技师</text>
				<text class="jump-text">点击跳转</text>
			</view>
			<view class="tips-item" v-if="!selectedServiceId" @tap="scrollToService">
				<text class="icon">●</text>
				<text>选择服务项目</text>
				<text class="jump-text">点击跳转</text>
			</view>
			<view class="tips-item" v-if="!selectedDate || !selectedTime" @tap="scrollToTime">
				<text class="icon">●</text>
				<text>选择服务时间</text>
				<text class="jump-text">点击跳转</text>
			</view>
		</view>
		<!-- 地图区域 -->
		<view class="map-container">
			<map class="store-map" :latitude="centerLatitude" :longitude="centerLongitude" :markers="storeMarkers"
				:scale="12" show-location @markertap="onMarkerTap"></map>
		</view>
		<!-- 门店列表 -->
		<scroll-view class="store-list" scroll-x="true" show-scrollbar="false"
			:scroll-into-view="'store-' + selectedStoreIndex" :scroll-with-animation="true" id="storeList">
			<view class="store-items">
				<view class="store-item" v-for="(store, index) in stores" :key="store.id" :id="'store-' + index"
					:class="{ active: selectedStoreIndex === index }" @tap="selectStore(index)">
					<view class="store-info">
						<image class="store-image" :src="store.image" mode="aspectFill"></image>
						<text class="store-name">{{ store.name }}</text>
						<text class="store-address">{{ store.address }}</text>
						<text class="store-phone" v-if="store.phone">
							<text class="phone-label">联系电话：</text>
							<text class="phone-number">{{ store.phone }}</text>
						</text>
					</view>
					<text class="select-btn" v-if="selectedStoreIndex === index">已选择</text>
				</view>
			</view>
		</scroll-view>
		<view class="technician-section">
			<view class="section-title">门店介绍</view>
			<view v-html="introduction"></view>
		</view>
		<view class="technician-section">
			<view class="section-title">门店设施</view>
			<view v-html="facilities"></view>
		</view>
		<!-- 技师列表 -->
		<view class="technician-section">
			<view class="section-title">选择技师</view>
			<scroll-view class="technician-list" scroll-x="true" show-scrollbar="false">
				<view class="technician-items">
					<view class="technician-item" v-for="(tech, index) in currentStoreTechnicians" :key="tech.id"
						:class="{ active: selectedTechId === tech.id }" @tap="selectTechnician(tech)">
						<image class="tech-avatar" :src="tech.avatar" mode="aspectFill"></image>
						<view class="tech-info">
							<text class="tech-name">{{ tech.name }}</text>
							<view class="tech-tags">
								<text class="tag">{{ tech.title }}</text>
								<text class="exp">{{ tech.experience }}年经验</text>
							</view>
							<view class="tech-rating">
								<text class="score">{{ tech.score }}分</text>
								<text class="orders">{{ tech.orders }}单</text>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<!-- 服务项目列表 -->
		<view class="service-section" v-if="selectedTechId">
			<view class="section-title">
				<text>选择服务项目</text>
				<text class="scroll-tip">可滚动查看更多</text>
			</view>
			<view class="service-list">
				<view class="service-item" v-for="service in currentTechServices" :key="service.id"
					:class="{ active: selectedServiceId === service.id }" @tap="selectService(service)">
					<image class="service-image" :src="service.image" mode="aspectFill"></image>
					<view class="service-content">
						<view class="service-header">
							<view class="service-duration">
								<text class="icon">⏱</text>
								<text>{{ service.duration }}分钟</text>
							</view>
						</view>
						<text class="service-desc">{{ service.desc }}</text>
						<view class="service-footer">
							<view class="price">
								<text class="symbol">¥</text>
								<text class="number">{{ service.price }}</text>
							</view>
							<text class="select-status" v-if="selectedServiceId === service.id">已选择</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="booking-form">
			<!-- 选择日期 -->
			<view class="form-item">
				<text class="label">预约日期</text>
				<view class="date-list">
					<view class="date-item" v-for="(date, index) in availableDates" :key="index"
						:class="{ active: selectedDate === date.value }" @tap="fetchAvailableTimes(date)">
						<text class="day">{{ date.day }}</text>
						<text class="date">{{ date.text }}</text>
					</view>
				</view>
			</view>
			{{selectedDate}}
			<!-- 选择时间 -->
			<view v-if="selectedDate" class="form-item">
				<view class="time-header">
					<text class="label">预约时间</text>
					<text class="scroll-tip">可滚动查看更多</text>
				</view>
				<view class="time-list">
					<view class="time-item" v-for="(time, index) in availableTimes" :key="index" :class="{ 
							active: selectedTime === time.timePoint,
							disabled: time.disabled
						}" @tap="selectTime(time)">
						<text class="time-text">{{ time.timePoint }}</text>
						<text class="duration-text"
							v-if="currentService.duration && time.value !== 'rest' && !time.disabled">
							{{ time.endTimePoint }}
							{{ time.duration }}
						</text>
					</view>
				</view>
			</view>
			<view class="form-item coupon-section" v-if="selectedServiceId">
				<text class="label">优惠券</text>
				<view class="coupon-list">
					<view class="coupon-item" v-for="coupon in availableCoupons" :key="coupon.id"
						:class="{ active: selectedCoupon && selectedCoupon.id === coupon.id }"
						@tap="selectCoupon(coupon)">
						<view class="coupon-info">
							<view class="coupon-name">{{ coupon.coupons.title }}</view>
							<view class="coupon-desc">{{ coupon.coupons.limitDesc }}</view>
							<view class="coupon-validity">有效期至：{{ coupon.expireTime }}</view>
						</view>
						<view class="coupon-amount">
							<text class="amount">￥{{ coupon.coupons.amount }}</text>
							<text class="condition"
								v-if="coupon.coupons.minAmount">满{{ coupon.coupons.minAmount }}可用</text>
						</view>
					</view>
					<view class="no-coupon" v-if="availableCoupons.length === 0">
						暂无可用优惠券
					</view>
				</view>
			</view>
			<view class="form-item member-card-section" v-if="selectedServiceId">
				<text class="label">会员卡</text>
				<view class="member-card-list">
					<view class="member-card-item" v-for="card in availableMemberCards" :key="card.id"
						:class="{ active: selectedMemberCard && selectedMemberCard.id === card.id }"
						@tap="selectMemberCard(card)">
						<view class="card-info">
							<view class="card-name">{{ card.memberCard.cardName }}</view>
							<view v-if="card.memberCard.cardType === 1" class="card-desc">
								余额：{{ card.balance }}元
							</view>
							<view v-if="card.memberCard.cardType === 2" class="card-desc">
								剩余次数：{{ card.remainingTimes }}次
							</view>
							<view class="card-validity">有效期至：{{ card.memberCard.expireTime }}</view>
						</view>
						<view class="card-action">
							<text class="action-text">
								{{ selectedMemberCard && selectedMemberCard.id === card.id ? '已选择' : '选择' }}
							</text>
						</view>
					</view>
					<view class="no-card" v-if="availableMemberCards.length === 0">
						暂无可用会员卡
					</view>
				</view>
			</view>
			<view class="gift-service-list" v-if="selectedMemberCard && giftProject && giftProject.status === true">
				<text class="label">附赠项目</text>
				<text class="label">- 剩余次数：{{ giftProject.num }}</text>
				<text class="label">- 有效期至: {{ giftProject.expireTime }}</text>
				<view class="gift-item" v-for="gift in giftProject.list" :key="gift.id" :class="{ 
						active: selectedGiftId === gift.id,
					}" @tap="selectGiftService(gift)">
					<view class="gift-info">
						<view class="left-info">
							<text class="name">{{ gift.projectName }}</text>
						</view>
					</view>
					<view class="action">
						<text class="action-text">
							{{ selectedGiftId === gift.id ? '已选择' : '选择' }}
						</text>
					</view>
				</view>
			</view>
			<view class="remark-section">
				<text class="label">备注</text>
				<textarea v-model="remark" placeholder="请输入备注信息（选填）" />
			</view>
		</view>
		<view style="position: fixed;left: 0;right: 0;bottom: 5%;">
			<uni-notice-bar show-icon scrollable
				text="感谢您选择我们的服务，出于对顾客的权益保护，本平台禁止任何线下交易，顾客和技师之间只使用平台虚拟号进行线上联系，一旦发现技师违反平台规定向顾客索要联系方式或进行私下交易，凭相关证据（视频或照片或语音），顾客可获得平台免单及现金奖励。" />
		</view>
		<view class="submit-bar">
			<view class="price-info">
				<text class="label">总计</text>
				<view class="price">
					<text class="symbol">¥</text>
					<text class="number">{{ totalPrice }}</text>
				</view>
			</view>
			<button class="submit-btn" @tap="submitBooking" :disabled="isSubmitting || isTechnician">
				{{ isSubmitting ? '提交中...' : (isTechnician ? '技师账号不可预约' : '确认预约') }}
			</button>
		</view>
	</view>
</template>
<script>
import NavBar from '@/components/nav-bar/nav-bar.vue';
import {request} from '@/utils/request.js';

export default {
		components: {
			NavBar
		},
		data() {
			return {
				giftProject: null,
				showUnselectedTips: true,
				// 地图中心点（北京市中心）
				centerLatitude: 39.908692,
				centerLongitude: 116.397477,
				// 修改为空数组，从接口获取数据
				stores: [],
				selectedStoreIndex: 0,
				storeMarkers: [], // 门店标记点
				selectedDate: '',
				selectedTime: '',
				availableDates: [],
				availableTimes: [],
				contact: '',
				phone: '',
				remark: '',
				selectedTechId: null,
				selectedServiceId: null,
				// 修改为空对象，从接口获取数据
				technicians: {},
				// 技师服务项目数据
				techServices: {},
				coupons: [], // 用户优惠券列表
				availableCoupons: [], // 可用优惠券列表
				selectedCoupon: null, // 选中的优惠券
				initPrice: 0,
				calculatedTotalPrice: 0, // 添加新的数据属性来存储计算后的总价
				memberCards: [], // 用户会员卡列表
				availableMemberCards: [], // 可用会员卡列表
				selectedMemberCard: null, // 选中的会员卡
				// 新增技师服务时间相关属性
				technicianServiceTimes: [], // 技师服务时间列表
				unavailableServiceTimes: [], // 不可用的时间段列表
				serviceDuration: [],
				servicedDuration: [],
				selectedCard: null,
				giftServices: [],
				projectList: [], // 添加项目列表
				isSubmitting: false, // 添加防止重复提交标志
				selectedGiftId: null, // 添加选中的礼品ID
				selectedGift: null, // 添加选中的赠送项目
				additionalServiceList: [], // 附加项目列表
				selectedAdditionalServices: [], // 已选择的附加项目ID列表
				additionalServicesMap: {}, // 附加项目映射，用于快速查找价格
				isTechnician: false, // 添加技师标识
				preSelectedServiceId: null, // 预选服务ID
				technicianWorkDays: '', // 保存工作日字符串供后续判断
			}
		},
		computed: {
			// 当前选中门店的技师列表
			currentStoreTechnicians() {
				const currentStore = this.stores[this.selectedStoreIndex]
				if (!currentStore) return []
				return this.technicians[currentStore.id] || []
			},
			// 当前选中技师的服务项目
			currentTechServices() {
				return this.techServices[this.selectedTechId] || []
			},
			// 当前选中的服务
			currentService() {
				if (!this.selectedServiceId) return {}
				return this.currentTechServices.find(service => service.id.toString() === this.selectedServiceId
					.toString()) || {}
			},
			// 计算总金额
			totalPrice() {
				return this.calculatedTotalPrice
			},
			// 获取当前选择的服务时长
			serviceDurations() {
				return this.currentService.duration || 0
			},
			// 门店介绍
			introduction() {
				const currentStore = this.stores[this.selectedStoreIndex]
				return currentStore ? currentStore.introduction || '' : ''
			},
			// 门店设施
			facilities() {
				const currentStore = this.stores[this.selectedStoreIndex]
				// 去除字符串中的html标签
				return currentStore ? currentStore.introduction || '' : ''
			}
		},
		watch: {
			selectedStoreIndex(val) {
				this.checkUnselectedItems()
			},
			selectedTechId(val) {
				this.checkUnselectedItems()
			},
			selectedServiceId: {
				handler(newVal) {
					// 当用户真正选择了服务后，清空 initPrice，避免与当前服务价格重复累计
					if (newVal && this.initPrice > 0) {
						this.initPrice = 0
					}
					this.updateAvailableCoupons()
					this.calculateTotalPrice()
					this.updateAvailableMemberCards()
					this.checkUnselectedItems()
				},
				immediate: true
			},
			selectedDate(val) {
				this.checkUnselectedItems()
			},
			selectedTime(val) {
				this.checkUnselectedItems()
			},
			selectedCoupon: {
				handler(newVal) {
					this.calculateTotalPrice()
					// 如果选择了优惠券，取消会员卡选择
					if (newVal) {
						this.selectedMemberCard = null
					}
				},
				immediate: true
			},
			selectedMemberCard: {
				handler(newVal) {
					this.calculateTotalPrice()
					// 如果选择了会员卡，取消优惠券选择
					if (newVal) {
						this.selectedCoupon = null
					}
				},
				immediate: true
			}
		},
		onLoad(options) {
			this.checkUserRole()
			// 处理传递的参数
			if (options) {
				if (options.serviceId) {
					this.preSelectedServiceId = options.serviceId
				}
				if (options.preSelectedServiceId) {
					this.preSelectedServiceId = options.preSelectedServiceId
				}
				if (options.priceCount) {
					this.initPrice += parseInt(options.priceCount)
					this.calculateTotalPrice()
				}
				if (options.code) {
					this.editUserOpenid(options.code)
				}
			}
			// 获取门店列表
			this.loadStores()
			// 获取技师列表
			this.loadTechnicians()
			// 设置日期范围
			const now = new Date()
			this.startDate = this.formatDate(now)
			now.setDate(now.getDate() + 30)
			this.endDate = this.formatDate(now)
			// 设置默认值
			this.date = this.startDate
			this.time = '09:00'
			this.initDateAndTime()
			// 加载用户优惠券
			this.loadUserCoupons()
			// 加载用户会员卡
			this.loadMemberCards()
			// 加载所有项目列表
			this.loadAllProjects()
			this.loadAdditionalServices() // 加载附加项目列表
		},
		onShow() {
			this.checkUserRole()
		},
		methods: {
			editUserOpenid(code) {
				let userInfo = uni.getStorageSync('userInfo')
				if (!userInfo) {
					uni.reLaunch({
						url: '/pages/login/login'
					})
				}
				uni.request({
					url: `${uni.$config.baseUrl}/wx/wx-service/getOauth2AccessToken`,
					method: 'GET',
					data: {
						code
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data.code === 200) {
							uni.request({
								url: `${uni.$config.baseUrl}/member/member/edit-open-id`,
								method: 'POST',
								data: {
									id: userInfo.memberId,
									openId: res.data.data.openid
								},
								success: (wxRes) => {
									if (wxRes.statusCode === 200 && wxRes.data.code === 200) {
										userInfo.openId = res.data.data.openid
										uni.setStorageSync('userInfo', userInfo)
									}
								}
							})
						}
					}
				})
			},
			// 返回上一页
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 加载门店列表
			loadStores() {
				uni.showLoading({
					title: '加载中...'
				})
				uni.request({
					url: `${uni.$config.baseUrl}/store/store/listALL`,
					method: 'GET',
					success: (res) => {
						if (res.data.code === 200) {
							// 处理门店数据
							this.stores = (res.data.rows || []).map(store => ({
								id: store.id,
								name: store.storeName || store.name,
								address: store.address || '',
								latitude: store.latitude || 39.908692,
								longitude: store.longitude || 116.397477,
								image: store.banner || 'https://picsum.photos/300/200?random=1',
								phone: store.contactPhone || '', // 添加联系电话字段
								introduction: store.introduction || '', // 门店介绍
								facilities: store.facilities || '', //门店设施
							}))
							// 如果有门店数据，初始化地图
							if (this.stores.length > 0) {
								// 设置第一个门店为中心点
								this.centerLatitude = this.stores[0].latitude
								this.centerLongitude = this.stores[0].longitude
								// 初始化地图标记
								this.initMapMarkers()
							} else {
								uni.showToast({
									title: '暂无门店数据',
									icon: 'none'
								})
							}
						} else {
							uni.showToast({
								title: '获取门店列表失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '获取门店列表失败',
							icon: 'none'
						})
					},
					complete: () => {
						uni.hideLoading()
					}
				})
			},
			// 初始化地图标记点
			initMapMarkers() {
				this.storeMarkers = this.stores.map((store, index) => {
					return {
						id: store.id,
						latitude: store.latitude,
						longitude: store.longitude,
						title: store.name,
						width: 32,
						height: 32,
						callout: {
							content: store.name,
							color: '#333333',
							fontSize: 14,
							borderRadius: 4,
							padding: 8,
							display: 'ALWAYS',
							textAlign: 'center'
						},
						iconPath: '/static/icons/store-marker1.png'
					}
				})
			},
			// 选择门店
			selectStore(index) {
				this.selectedStoreIndex = index
				this.selectedTechId = null // 重置技师选择
				this.selectedCard = null
				this.selectedCoupon = null
				this.selectedDate = null
				this.selectedGift = null
				this.selectedGiftId = null
				this.selectedMemberCard = null
				// 将地图中心移动到选中的门店
				const store = this.stores[index]
				this.centerLatitude = store.latitude
				this.centerLongitude = store.longitude
				// 滚动到对应的门店卡片
				this.$nextTick(() => {
					const query = uni.createSelectorQuery()
					query.select('#storeList').node()
					query.exec((res) => {
						if (res[0]) {
							res[0].scrollIntoView({
								selector: `#store-${index}`,
								duration: 300
							})
						}
					})
				})
				uni.showToast({
					title: `已选择${store.name}`,
					icon: 'none'
				})
			},
			// 点击地图标记
			onMarkerTap(e) {
				const markerId = e.detail.markerId
				const storeIndex = this.stores.findIndex(store => store.id === markerId)
				if (storeIndex !== -1) {
					this.selectStore(storeIndex)
				}
			},
			// 选择门店（picker）
			onStoreChange(e) {
				const index = e.detail.value
				this.selectStore(index)
			},
			formatDate(date) {
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				return `${year}-${month}-${day}`
			},
			onDateChange(e) {
				this.date = e.detail.value
			},
			onTimeChange(e) {
				this.time = e.detail.value
			},
			// 初始化日期和时间
			initDateAndTime() {
				// 生成可选日期（今天、明天、后天）
				const dates = []
				const dayNames = ['今天', '明天', '后天']
				for (let i = 0; i < 3; i++) {
					const date = new Date()
					date.setDate(date.getDate() + i)
					dates.push({
						value: this.formatDate(date),
						text: `${date.getMonth() + 1}月${date.getDate()}日`,
						day: dayNames[i]
					})
				}
				this.availableDates = dates
				// this.selectedDate = dates[0].value
				// 更新可选时间
				// this.getTechnicianServiceTimes(this.techInfo.id, this.selectedDate)
				// this.updateAvailableTimes()
			},
			// 调用后端接口获取时间段
			fetchAvailableTimes(dateStr) {
				this.selectedDate = dateStr.value
				this.unavailableServiceTimes = []
				uni.request({
					url: `${uni.$config.baseUrl}/servicetime/servicetime/get-server-time-list`,
					method: 'POST',
					header: {
						'content-type': 'application/json'
					},
					data: {
						date: dateStr.value,
						techId: this.selectedTechId,
						duration: this.currentService.duration,
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data.code === 200) {
							this.availableTimes = (res.data.data || [])
						} else {
							uni.showToast({
								title: '请选择技师和项目',
								icon: 'error',
								duration: 2000
							})
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '请选择技师和项目',
							icon: 'error',
							duration: 2000
						})
					}
				})
			},
			// 旧逻辑封装为回退
			fallbackGenerateTimes() {
				const now = new Date()
				const isToday = this.selectedDate === this.formatDate(now)
				this.generateDefaultTimeSlots(isToday, now.getHours(), now.getMinutes())
			},
			// 更新可选时间（入口）
			updateAvailableTimes() {
				const now = new Date()
				const isToday = this.selectedDate === this.formatDate(now)
				const currentHour = now.getHours()
				const currentMinute = now.getMinutes()
				// 未选择完整信息时使用本地默认生成
				this.generateDefaultTimeSlots(isToday, currentHour, currentMinute)
			},
			// 生成默认时间选项（10:00-22:00，每半小时一个时间段）
			generateDefaultTimeSlots(isToday, currentHour, currentMinute) {
				const times = []
				// 生成10:00-22:00的时间选项，每半小时一个时间段
				for (let hour = 8; hour < 24; hour++) {
					for (let minute = 0; minute < 60; minute += 30) {
						const timeValue = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
						const disabled = isToday && (hour < currentHour || (hour === currentHour && minute <=
							currentMinute))
						times.push({
							value: timeValue,
							text: timeValue,
							disabled
						})
					}
				}
				this.availableTimes = times
			},
			// 检查时间段是否可用（考虑服务时长和技师已预约时间）
			isTimeSlotAvailable(time) {
				if (!this.currentService.duration) return true
				const [hour, minute] = time.value.split(':').map(Number)
				const endTime = new Date()
				endTime.setHours(hour)
				endTime.setMinutes(minute + this.currentService.duration)
				// 检查服务结束时间是否超过营业时间（22:00）
				if (endTime.getHours() >= 24 && endTime.getMinutes() > 0) {
					return false
				}
				// 检查是否在技师不可服务的时间范围内
				if (this.unavailableServiceTimes && this.unavailableServiceTimes.length > 0) {
					const timeStr = time.value
					if (this.unavailableServiceTimes.includes(timeStr)) {
						return false
					}
				}
				return true
			},
			// 获取服务结束时间
			getEndTime(startTime) {
				if (!startTime || !this.currentService.duration) return ''
				const [hour, minute] = startTime.split(':').map(Number)
				const endTime = new Date()
				endTime.setHours(hour)
				endTime.setMinutes(minute + this.currentService.duration)
				return `至 ${endTime.getHours().toString().padStart(2, '0')}:${endTime.getMinutes().toString().padStart(2, '0')}`
			},
			generateHalfHourIntervals(startTime, endTime) {
				// 将时间字符串转换为分钟数
				const [startHour, startMinute] = startTime.split(':').map(Number);
				const [endHour, endMinute] = endTime.split(':').map(Number);
				const startMinutes = startHour * 60 + startMinute;
				const endMinutes = endHour * 60 + endMinute;
				// 验证时间顺序
				if (startMinutes > endMinutes) {
					return [];
				}
				// 生成每半小时的时间点
				const intervals = [];
				for (let minutes = startMinutes; minutes <= endMinutes; minutes += 30) {
					const hour = Math.floor(minutes / 60);
					const minute = minutes % 60;
					intervals.push(`${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`);
				}
				return intervals;
			},
			// 获取技师服务时间
			async getServiceTimes(technicianId, appointmentDate) {
				try {
					// 第一步：尝试从技师服务时间表获取数据
					const res = await uni.request({
						url: `${uni.$config.baseUrl}/servicetime/servicetime/listAll`,
						method: 'GET',
						data: {
							techId: technicianId,
							serviceDate: appointmentDate // 格式为yyyy-MM-dd
						}
					})
					// 检查是否成功获取数据
					if (res.statusCode === 200 && res.data.code === 200) {
						// 如果获取到了数据
						if (res.data.rows && res.data.rows.length > 0) {
							// 保存技师服务时间数据
							this.technicianServiceTimes = res.data.rows || []
							// 解析不可用时间段
							this.parseUnavailableTimes(res.data.rows)
							// 生成技师可用的时间段
							this.generateTechnicianTimeSlots(res.data.rows)
						} else {
							// 如果没有获取到数据，尝试获取技师工作排班
							await this.getTechnicianWorkSchedule(technicianId, appointmentDate)
						}
					} else {
						// 尝试获取技师工作排班
						await this.getTechnicianWorkSchedule(technicianId, appointmentDate)
					}
				} catch (error) {
					// 尝试获取技师工作排班
					await this.getTechnicianWorkSchedule(technicianId, appointmentDate)
				}
			},
			// 获取技师工作排班
			async getTechnicianWorkSchedule(technicianId, serviceDate) {
				try {
					const res = await uni.request({
						url: `${uni.$config.baseUrl}/schedule/schedule/listAll`,
						method: 'GET',
						data: {
							technicianId: technicianId,
						}
					})
					if (res.statusCode === 200 && res.data.code === 200 && res.data.rows && res.data.rows.length > 0) {
						// 校验今日是否休息
						const [year, month, day] = serviceDate.split('-').map(Number);
						const dayOfWeek = new Date(year, month - 1, day).getDay();
						if (res.data.rows && !res.data.rows[0].workDays.split(',').find(i => Number(i) === (
								dayOfWeek === 0 ? 7 : dayOfWeek))) {
							this.unavailableServiceTimes = this.generateHalfHourIntervals(res.data.rows[0].startTime,
								res.data.rows[0].endTime)
						}
						// 将工作排班数据转换为服务时间格式
						this.technicianServiceTimes = res.data.rows.map(schedule => {
							return {
								startTime: schedule.startTime,
								endTime: schedule.endTime,
								workDays: schedule.workDays,
								serviceDuration: '',
								servicedDuration: ''
							}
						})
						// 生成技师可用的时间段
						this.generateTechnicianTimeSlots(this.technicianServiceTimes)
						console.log('获取技师工作排班成功:', res.data.rows)
						// 保存工作日字符串供后续判断
						this.technicianWorkDays = res.data.rows[0].workDays || '';
					} else {
						this.technicianServiceTimes = []
						this.unavailableServiceTimes = []
						// 使用默认时间段
						const now = new Date()
						const isToday = this.selectedDate === this.formatDate(now)
						this.generateDefaultTimeSlots(isToday, now.getHours(), now.getMinutes())
					}
				} catch (error) {
					this.technicianServiceTimes = []
					this.unavailableServiceTimes = []
					// 使用默认时间段
					const now = new Date()
					const isToday = this.selectedDate === this.formatDate(now)
					this.generateDefaultTimeSlots(isToday, now.getHours(), now.getMinutes())
				}
			},
			// 生成技师可用的时间段
			generateTechnicianTimeSlots(serviceTimes) {
				const times = []
				const now = new Date()
				const isToday = this.selectedDate === this.formatDate(now)
				const currentHour = now.getHours()
				const currentMinute = now.getMinutes()
				// 只有当有服务时间数据时才处理
				if (serviceTimes && serviceTimes.length > 0) {
					// 整体校验：若所有记录的 workDays 都不包含当前星期，则直接无可用时间
					if (serviceTimes && serviceTimes.length > 0) {
						const dow = (() => {
							const d = new Date(this.selectedDate).getDay();
							return d === 0 ? 7 : d
						})()
						let hasWorkingDay = serviceTimes.some(st => {
							if (!st.workDays) return false;
							return st.workDays.split(',').filter(Boolean).map(Number).includes(dow)
						})
						// 如果所有serviceTime都没有workDays字段，则使用技师排班workDays判断
						if (!hasWorkingDay && this.technicianWorkDays) {
							const dayArr = this.technicianWorkDays.split(',').filter(Boolean).map(Number);
							hasWorkingDay = dayArr.includes(dow);
						}
						if (!hasWorkingDay) {
							this.availableTimes = [{
								value: 'rest',
								text: '— 技师今日休息 —',
								disabled: true
							}];
							return;
						}
					}
					// 处理每个服务时间记录
					for (const serviceTime of serviceTimes) {
						// 根据技师的 workDays 判断是否休息日，若为休息则跳过
						if (serviceTime.workDays !== undefined && serviceTime.workDays !== null) {
							const dayOfWeek = new Date(this.selectedDate).getDay(); // 0:周日
							const dayNum = dayOfWeek === 0 ? 7 : dayOfWeek; // 1-7
							const allowed = serviceTime.workDays.split(',').filter(Boolean).map(Number);
							// 如果workDays为空，表示无工作日；或当天不在允许列表
							if (allowed.length === 0 || !allowed.includes(dayNum)) {
								continue;
							}
						}
						if (serviceTime.startTime && serviceTime.endTime) {
							// 解析开始和结束时间
							const [startHour, startMinute] = serviceTime.startTime.split(':').map(Number)
							const [endHour, endMinute] = serviceTime.endTime.split(':').map(Number)
							// 计算起始和结束时间（分钟）
							const startMinutes = startHour * 60 + startMinute
							const endMinutes = endHour * 60 + endMinute
							// 生成从开始到结束时间的每个时间段，每30分钟一个
							for (let m = startMinutes; m <= endMinutes; m += 30) {
								const hour = Math.floor(m / 60)
								const minute = m % 60
								const timeValue =
									`${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
								// 判断是否为今天且时间已过
								const disabled = isToday && (hour < currentHour || (hour === currentHour && minute <=
									currentMinute))
								// 检查是否已经在不可用时间列表中
								const unavailable = this.unavailableServiceTimes.includes(timeValue)
								// 添加到时间列表中，只有未过时且未被占用的时间才可选
								times.push({
									value: timeValue,
									text: timeValue,
									disabled: disabled || unavailable
								})
							}
						}
					}
					// 按时间排序
					times.sort((a, b) => {
						const [aHour, aMinute] = a.value.split(':').map(Number)
						const [bHour, bMinute] = b.value.split(':').map(Number)
						if (aHour !== bHour) {
							return aHour - bHour
						}
						return aMinute - bMinute
					})
					// 对时间段做一次去重处理，避免出现相同时间显示两次
					const dedupedMap = new Map()
					for (const item of times) {
						// 如果已存在该时间，则根据 disabled 状态做合并：只要有一次被禁用则保持禁用
						if (dedupedMap.has(item.value)) {
							const existing = dedupedMap.get(item.value)
							existing.disabled = existing.disabled || item.disabled
						} else {
							dedupedMap.set(item.value, {
								...item
							})
						}
					}
					const dedupedTimes = Array.from(dedupedMap.values())
					// 再次按时间升序（Map保持插入顺序，但稳妥起见再排序一次）
					dedupedTimes.sort((a, b) => {
						const [aHour, aMinute] = a.value.split(':').map(Number)
						const [bHour, bMinute] = b.value.split(':').map(Number)
						return (aHour * 60 + aMinute) - (bHour * 60 + bMinute)
					})
					// 更新可用时间
					this.availableTimes = dedupedTimes
				} else {
					// 如果没有服务时间数据，使用默认时间
					this.generateDefaultTimeSlots(isToday, currentHour, currentMinute)
				}
			},
			// 解析不可用的时间段
			parseUnavailableTimes(serviceTimes) {
				this.unavailableServiceTimes = []
				if (!serviceTimes || serviceTimes.length === 0) return
				for (const serviceTime of serviceTimes) {
					// 解析serviceDuration（已经预约的时间段）
					if (serviceTime.serviceDuration) {
						const times = serviceTime.serviceDuration.split(',')
						this.unavailableServiceTimes.push(...times)
					}
					// 解析servicedDuration（技师自己设置的不可服务时间段）
					if (serviceTime.servicedDuration) {
						const times = serviceTime.servicedDuration.split(',')
						this.unavailableServiceTimes.push(...times)
					}
				}
				// 去重
				this.unavailableServiceTimes = [...new Set(this.unavailableServiceTimes)]
			},
			// 选择日期
			selectDate(date) {
				this.selectedDate = date.value
				this.unavailableServiceTimes = []
				// 更新可选时间
				this.updateAvailableTimes()
			},
			// 选择时间
			selectTime(time) {
				if (!time.disabled) {
					this.selectedTime = time.timePoint
				}
			},
			// 提交预约
			submitBooking() {
				if (this.isSubmitting) {
					uni.showToast({
						title: '请勿重复提交',
						icon: 'none'
					})
					return
				}
				if (this.isTechnician) {
					uni.showModal({
						title: '提示',
						content: '您当前登录的账号为技师账号，不可预约',
						showCancel: false,
						confirmText: '知道了'
					})
					return
				}
				if (this.selectedStoreIndex === null) {
					uni.showToast({
						title: '请选择门店',
						icon: 'none'
					})
					return
				}
				if (!this.selectedTechId) {
					uni.showToast({
						title: '请选择技师',
						icon: 'none'
					})
					return
				}
				if (!this.selectedServiceId) {
					uni.showToast({
						title: '请选择服务项目',
						icon: 'none'
					})
					return
				}
				if (!this.selectedDate) {
					uni.showToast({
						title: '请选择预约日期',
						icon: 'none'
					})
					return
				}
				if (!this.selectedTime) {
					uni.showToast({
						title: '请选择预约时间',
						icon: 'none'
					})
					return
				}
				if (this.selectedMemberCard) {
					const card = this.selectedMemberCard
					if (card.memberCard.cardType === 1) { // 充值卡
						if (card.balance < this.totalPrice) {
							uni.showToast({
								title: '充值卡余额不足',
								icon: 'none'
							})
							return
						}
					} else if (card.memberCard.cardType === 2) { // 次卡
						if (card.remainingTimes <= 0) {
							uni.showToast({
								title: '会员卡次数不足',
								icon: 'none'
							})
							return
						}
					}
				}
				const userInfo = uni.getStorageSync('userInfo')
				if (!userInfo.openId) {
					uni.showModal({
						title: '微信授权提示',
						content: '首次支付需要绑定微信账号，是否立即前往授权？',
						confirmText: '去授权',
						cancelText: '取消',
						success: res => {
							if (res.confirm) {
								const currentUrl = encodeURIComponent(window.location.href);
								const appId = uni.$config.wxAppId;
								const redirectUrl =
									`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${currentUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
								window.location.href = redirectUrl;
							}
						},
						fail: (err) => {
							uni.showToast({
								title: JSON.stringify(err),
								icon: 'none',
								duration: 2000
							});
						},
					});
					return
				}
				// 设置提交状态为true，防止重复提交
				this.isSubmitting = true
				// 获取用户信息
				// 构建预约订单数据
				const appointmentOrders = {
					userId: userInfo.memberId,
					orderType: 1, // 1-预约到店
					img: this.currentService.image,
					serviceId: this.currentService.id,
					serviceName: this.currentService.name,
					servicePrice: this.currentService.price,
					serviceDuration: this.currentService.duration,
					// 技师信息
					technicianId: this.selectedTechId,
					technicianName: this.currentStoreTechnicians.find(techInfo => techInfo.id === this.selectedTechId)
						?.name,
					// 预约时间信息
					appointmentDate: this.selectedDate,
					appointmentTime: this.selectedTime + ":00",
					// 门店信息
					storeId: this.stores[this.selectedStoreIndex].id,
					storeName: this.stores[this.selectedStoreIndex].name,
					storeAddress: this.stores[this.selectedStoreIndex].address,
					// 订单状态
					orderStatus: this.selectedMemberCard ? 1 : 0,
					paymentStatus: this.selectedMemberCard ? 1 : 0, // 会员卡支付时为1（已支付），否则为0（未支付）
					paymentAmount: this.totalPrice,
					// 备注信息
					remark: this.remark.trim(),
					// 优惠券和会员卡ID
					couponId: this.selectedCoupon ? this.selectedCoupon.id : null,
					cardId: this.selectedMemberCard ? this.selectedMemberCard.id : null,
					giftServiceId: this.selectedGift && this.selectedGift.id ? this.selectedGift.id : null,
					// 添加附加服务信息
					additionalService: this.selectedAdditionalServices.map(id => {
						const service = this.additionalServicesMap[id]
						return service.projectName
					}).join(','),
				}
				// 显示加载中
				uni.showLoading({
					title: '提交中...'
				})
				if (appointmentOrders.couponId) {
					if (!this.selectedCoupon.coupons.amount) {
						uni.showToast({
							title: '会员卡暂无金额',
							icon: 'error',
							duration: 2000
						})
						return
					}
					const amount = appointmentOrders.paymentAmount - this.selectedCoupon.coupons.amount
					appointmentOrders.paymentAmount = amount < 0 ? 0 : amount
					appointmentOrders.orderStatus = 1
					appointmentOrders.paymentStatus = 1
				}
				// 调用后端接口
				uni.request({
					url: `${uni.$config.baseUrl}/orders/orders`,
					method: 'POST',
					data: appointmentOrders,
					success: async (res) => {
						if (res.statusCode === 200 && res.data.code === 200) {
							let orderid = res.data.data
							// 如果使用了优惠券，更新优惠券状态
							if (this.selectedCoupon) {
								if (appointmentOrders.paymentAmount <= 0) {
									setTimeout(() => {
										uni.navigateTo({
											url: '/pages/my-orders/my-orders'
										})
									}, 2000)
								}
								return
							}
							// 如果使用会员卡，不需要调用支付接口，直接跳转到订单页面
							if (this.selectedMemberCard) {
								uni.showToast({
									title: '预约成功',
									icon: 'success',
									duration: 2000,
									success: () => {
										setTimeout(() => {
											uni.navigateTo({
												url: '/pages/my-orders/my-orders'
											})
										}, 2000)
									}
								})
								return
							}
							// 创建微信订单
							this.createWxPayOrder(orderid)
							/* uni.request({
								url: `${uni.$config.baseUrl}/orders/orders/createWxPayOrder/${orderid}`,
								method: 'POST',
								success: (payRes) => {
									if (payRes.statusCode === 200 && payRes.data.code === 200) {
										if (1 === 1) {
											const paymentData = {
												payAmount: this.totalPrice,
												orderType: 3,
												orderDesc: this.currentService.name,
												callbackUrl: '/pages/my-orders/my-orders?a=1',
												paymentParams: {
													orderId: orderid,
													timeStamp: payRes.data.data.timeStamp,
													nonceStr: payRes.data.data.nonceStr,
													package: `prepay_id=${payRes.data.data.prepayId}`,
													paySign: payRes.data.data.paySign,
												},
											}
											uni.setStorageSync("paymentData", paymentData)
											uni.redirectTo({
												url: '/pages/pay-public/pay-public?login=false',
											})
											return
										}
										let payData = payRes.data.data
										// #ifdef H5
										// H5环境处理
										const isWechatBrowser = /MicroMessenger/i.test(navigator
											.userAgent);
										if (isWechatBrowser) {
											// 微信公众号H5环境
											if (typeof WeixinJSBridge === 'undefined') {
												// 如果WeixinJSBridge对象不存在，则通过事件监听创建
												document.addEventListener('WeixinJSBridgeReady',
													() => {
														this.callWechatH5Pay(payData, orderid);
													}, false);
											} else {
												// 如果WeixinJSBridge对象已经存在，直接调用
												this.callWechatH5Pay(payData, orderid);
											}
										} else {
											// 非微信浏览器
											uni.showModal({
												title: '提示',
												content: '请在微信浏览器中打开进行支付',
												showCancel: false,
												success: () => {
													this.isSubmitting = false;
												}
											});
										}
										// #endif
										// #ifdef MP-WEIXIN
										// 小程序环境支付
										uni.requestPayment({
											provider: 'wxpay',
											timeStamp: payData.timeStamp,
											nonceStr: payData.nonceStr,
											package: payData.package,
											signType: 'RSA',
											paySign: payData.paySign,
											success: (res) => {
												// 更新订单支付状态为已支付
												this.updateOrderPaymentStatus(orderid,
													1)
												uni.showToast({
													title: '支付成功',
													icon: 'success',
													duration: 2000,
													// success: () => {
													// 	setTimeout(() => {
													// 		uni.navigateTo({
													// 			url: '/pages/my-orders/my-orders'
													// 		})
													// 	}, 2000)
													// }
												})
											},
											fail: (err) => {
												console.error('支付失败:', err)
												uni.showToast({
													title: err.errMsg ===
														'requestPayment:fail cancel' ?
														'支付取消' : '支付失败',
													icon: 'none'
												})
												this.isSubmitting = false;
											},
											complete: () => {
												this.isSubmitting = false;
											}
										})
										// #endif
										// #ifdef APP-PLUS
										// App环境支付
										uni.requestPayment({
											provider: 'wxpay',
											orderInfo: payData, // App环境可能需要完整的订单信息
											success: (res) => {
												uni.showToast({
													title: '支付成功',
													icon: 'success',
													duration: 2000,
													success: () => {
														setTimeout(() => {
															uni.navigateTo({
																url: '/pages/my-orders/my-orders'
															})
														}, 2000)
													}
												})
											},
											fail: (err) => {
												console.error('支付失败:', err)
												uni.showToast({
													title: '支付失败',
													icon: 'none'
												})
												this.isSubmitting = false;
											},
											complete: () => {
												this.isSubmitting = false;
											}
										})
										// #endif
										// #ifndef H5 || MP-WEIXIN || APP-PLUS
										// 开发环境或其他环境
										uni.showModal({
											title: '开发环境提示',
											content: '当前环境不支持微信支付功能，仅在微信环境中可用。是否模拟支付成功？',
											confirmText: '模拟成功',
											cancelText: '模拟失败',
											success: (res) => {
												if (res.confirm) {
													// 更新订单支付状态为已支付
													this.updateOrderPaymentStatus(
														orderid, 1)
													uni.showToast({
														title: '支付成功(模拟)',
														icon: 'success',
														duration: 2000,
														success: () => {
															setTimeout(
																() => {
																	uni.navigateTo({
																		url: '/pages/my-orders/my-orders'
																	})
																}, 2000
															)
														}
													})
												} else {
													// 模拟支付失败
													uni.showToast({
														title: '支付取消(模拟)',
														icon: 'none'
													})
												}
												this.isSubmitting = false;
											}
										})
										// #endif
									} else if () {
										
									} else {
										uni.showToast({
											title: payRes.data.msg || '支付创建失败',
											icon: 'none'
										})
										this.isSubmitting = false;
									}
								},
								fail: (err) => {
									console.error('调用支付接口失败:', err)
									uni.showToast({
										title: '支付创建失败',

										icon: 'none'
									})
									this.isSubmitting = false;
								}
							}) */
						} else {
							uni.showToast({
								title: res.data.msg || '预约失败',
								icon: 'none'
							})
							// 预约失败，重置提交状态
							this.isSubmitting = false
						}
					},
					fail: (err) => {
						console.error('预约失败:', err)
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						})
						// 网络请求失败，重置提交状态
						this.isSubmitting = false
					},
					complete: () => {
						uni.hideLoading()
						// 如果使用会员卡，在complete中重置状态（因为会员卡支付流程没有requestPayment的complete回调）
						if (this.selectedMemberCard) {
							this.isSubmitting = false
						}
					}
				})
			},
			createWxPayOrder(orderid) {
				uni.request({
					url: `${uni.$config.baseUrl}/orders/orders/createWxPayOrder/${orderid}`,
					method: 'POST',
					success: (payRes) => {
						if (payRes.statusCode === 200 && payRes.data.code === 200) {
							if (1 === 1) {
								const paymentData = {
									payAmount: this.totalPrice,
									orderType: 3,
									orderDesc: this.currentService.name,
									callbackUrl: '/pages/my-orders/my-orders?a=1',
									paymentParams: {
										orderId: orderid,
										timeStamp: payRes.data.data.timeStamp,
										nonceStr: payRes.data.data.nonceStr,
										package: `prepay_id=${payRes.data.data.prepayId}`,
										paySign: payRes.data.data.paySign,
									},
								}
								uni.setStorageSync("paymentData", paymentData)
								uni.redirectTo({
									url: '/pages/pay-public/pay-public?login=false',
								})
								return
							}
							let payData = payRes.data.data
							// #ifdef H5
							// H5环境处理
							const isWechatBrowser = /MicroMessenger/i.test(navigator
								.userAgent);
							if (isWechatBrowser) {
								// 微信公众号H5环境
								if (typeof WeixinJSBridge === 'undefined') {
									// 如果WeixinJSBridge对象不存在，则通过事件监听创建
									document.addEventListener('WeixinJSBridgeReady',
										() => {
											this.callWechatH5Pay(payData, orderid);
										}, false);
								} else {
									// 如果WeixinJSBridge对象已经存在，直接调用
									this.callWechatH5Pay(payData, orderid);
								}
							} else {
								// 非微信浏览器
								uni.showModal({
									title: '提示',
									content: '请在微信浏览器中打开进行支付',
									showCancel: false,
									success: () => {
										this.isSubmitting = false;
									}
								});
							}
							// #endif
							// #ifdef MP-WEIXIN
							// 小程序环境支付
							uni.requestPayment({
								provider: 'wxpay',
								timeStamp: payData.timeStamp,
								nonceStr: payData.nonceStr,
								package: payData.package,
								signType: 'RSA',
								paySign: payData.paySign,
								success: (res) => {
									// 更新订单支付状态为已支付
									this.updateOrderPaymentStatus(orderid,
										1)
									uni.showToast({
										title: '支付成功',
										icon: 'success',
										duration: 2000,
									})
								},
								fail: (err) => {
									console.error('支付失败:', err)
									uni.showToast({
										title: err.errMsg ===
											'requestPayment:fail cancel' ?
											'支付取消' : '支付失败',
										icon: 'none'
									})
									this.isSubmitting = false;
								},
								complete: () => {
									this.isSubmitting = false;
								}
							})
							// #endif
							// #ifdef APP-PLUS
							// App环境支付
							uni.requestPayment({
								provider: 'wxpay',
								orderInfo: payData, // App环境可能需要完整的订单信息
								success: (res) => {
									uni.showToast({
										title: '支付成功',
										icon: 'success',
										duration: 2000,
										success: () => {
											setTimeout(() => {
												uni.navigateTo({
													url: '/pages/my-orders/my-orders'
												})
											}, 2000)
										}
									})
								},
								fail: (err) => {
									console.error('支付失败:', err)
									uni.showToast({
										title: '支付失败',
										icon: 'none'
									})
									this.isSubmitting = false;
								},
								complete: () => {
									this.isSubmitting = false;
								}
							})
							// #endif
						} else {
							uni.showToast({
								title: payRes.data.msg || '支付创建失败',
								icon: 'none'
							})
							this.isSubmitting = false;
						}
					},
					fail: (err) => {
						console.error('调用支付接口失败:', err)
						uni.showToast({
							title: '支付创建失败',

							icon: 'none'
						})
						this.isSubmitting = false;
					}
				})
			},
			// 减少附赠项目次数
			decreaseGiftServiceTimes() {
				if (!this.selectedGiftId) {
					return;
				}
				uni.request({
					url: `${uni.$config.baseUrl}/cardgiftuser/cardgiftuser/decreaseTimes`,
					method: 'POST',
					data: {
						id: this.selectedGiftId,
						times: 1, // 每次减少1次
						memberId: this.getCurrentMemberId() // 使用统一方法获取memberId
					},
					success: (res) => {
						if (res.data.code === 200) {} else {}
					},
					fail: (err) => {}
				});
			},
			// 减少会员卡次数或金额
			decreaseCardTimes() {
				if (!this.selectedMemberCard || !this.selectedMemberCard.id) {
					return;
				}
				// 根据会员卡类型决定是减少次数还是减少金额
				if (this.selectedMemberCard.memberCard.cardType === 1) {
					// 充值卡类型，减少金额
					this.decreaseCardBalance();
				} else {
					// 次卡类型，减少次数
					this.decreaseCardTimesOnly();
				}
			},
			// 减少会员卡次数
			decreaseCardTimesOnly() {
				if (!this.selectedMemberCard || !this.selectedMemberCard.id) {
					return;
				}
				uni.request({
					url: `${uni.$config.baseUrl}/usercard/usercard/decreaseTimes`,
					method: 'POST',
					data: {
						id: this.selectedMemberCard.id,
						times: 1, // 每次减少1次
						memberId: this.getCurrentMemberId() // 使用统一方法获取memberId
					},
					success: (res) => {
						if (res.data.code === 200) {} else {}
					},
					fail: (err) => {}
				});
			},
			// 减少会员卡余额
			decreaseCardBalance() {
				if (!this.selectedMemberCard || !this.selectedMemberCard.id) {
					return;
				}
				// 获取已选择的服务信息
				const selectedServiceInfo = this.services.find(s => s.id === this.selectedService);
				if (!selectedServiceInfo) {
					return;
				}
				// 计算需要扣除的金额
				const deductAmount = selectedServiceInfo.price;
				uni.request({
					url: `${uni.$config.baseUrl}/usercard/usercard/decreaseBalance`,
					method: 'POST',
					data: {
						id: this.selectedMemberCard.id,
						amount: deductAmount, // 扣除服务价格
						memberId: this.getCurrentMemberId() // 使用统一方法获取memberId
					},
					success: (res) => {
						if (res.data.code === 200) {} else {}
					},
					fail: (err) => {}
				});
			},
			// 选择技师
			selectTechnician(techInfo) {
				this.unavailableServiceTimes = []
				this.availableTimes = []
				this.selectedTechId = techInfo.id
				this.selectedServiceId = null
				// 加载技师的项目列表
				this.loadTechnicianProjects(techInfo.id)
				// 如果已选择日期，则更新时间选择
				if (this.selectedDate) {
					this.updateAvailableTimes()
				}
				uni.showToast({
					title: `已选择${techInfo.name}`,
					icon: 'none'
				})
			},
			// 选择服务项目
			selectService(service) {
				this.selectedServiceId = service.id
				// 重新检查时间选择是否有效
				this.updateAvailableTimes()
				uni.showToast({
					title: `已选择${service.name}`,
					icon: 'none'
				})
			},
			// 加载技师的项目列表
			loadTechnicianProjects(technicianId) {
				uni.showLoading({
					title: '加载中...'
				})
				uni.request({
					url: `${uni.$config.baseUrl}/project/project/technician/${technicianId}`,
					method: 'GET',
					success: (res) => {
						if (res.data.code === 200) {
							// 处理项目数据
							const projects = (res.data.rows || []).map(project => ({
								id: project.id,
								name: project.projectName,
								desc: project.projectDesp || '暂无描述',
								price: project.price || '0',
								duration: project.duration || 60,
								image: project.imgUrls ? project.imgUrls.split(',')[0] :
									'https://picsum.photos/300/200?random=21'
							}))
							// 更新技师的服务列表
							this.$set(this.techServices, technicianId, projects)
							// 如果有预选服务ID，自动选择对应的服务
							if (this.preSelectedServiceId) {
								const preSelectedService = projects.find(project =>
									project.id.toString() === this.preSelectedServiceId.toString()
								)
								if (preSelectedService) {
									this.selectedServiceId = preSelectedService.id
									// 使用nextTick确保数据更新后再计算价格
									this.$nextTick(() => {
										this.calculateTotalPrice()
									})
								} else {
									uni.showToast({
										title: '该技师暂不支持预选服务',
										icon: 'none',
										duration: 2000 // 设置为1秒（1000毫秒）
									})
								}
							}
						} else {
							uni.showToast({
								title: '获取项目列表失败',
								icon: 'none'
							})
							// 设置空数组防止页面报错
							this.$set(this.techServices, technicianId, [])
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '获取项目列表失败',
							icon: 'none'
						})
						// 设置空数组防止页面报错
						this.$set(this.techServices, technicianId, [])
					},
					complete: () => {
						uni.hideLoading()
					}
				})
			},
			// 加载技师列表
			loadTechnicians() {
				uni.showLoading({
					title: '加载中...'
				})
				uni.request({
					url: `${uni.$config.baseUrl}/technician/technician/listByStores`,
					method: 'GET',
					success: (res) => {
						if (res.data.code === 200) {
							// 处理技师数据
							const techData = res.data.data.technicians || {}
							// 转换数据格式
							this.technicians = Object.keys(techData).reduce((acc, storeId) => {
								acc[storeId] = techData[storeId].map(tech => ({
									id: tech.id,
									name: tech.name,
									title: tech.title || '推拿师',
									experience: tech.experience || 0,
									score: tech.score || 5.0,
									orders: tech.orders || 0,
									avatar: tech.avatar ||
										'https://picsum.photos/200/200?random=1'
								}))
								return acc
							}, {})
						} else {
							uni.showToast({
								title: '获取技师列表失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '获取技师列表失败',
							icon: 'none'
						})
					},
					complete: () => {
						uni.hideLoading()
					}
				})
			},

			// 加载用户优惠券
			loadUserCoupons() {
				const userInfo = uni.getStorageSync('userInfo')
				if (!userInfo || !userInfo.memberId) {
					return
				}
				uni.request({
					url: `${uni.$config.baseUrl}/usercoupons/usercoupons/listAllByUserId/${userInfo.memberId}`,
					method: 'GET',
					success: (res) => {
						if (res.statusCode === 200 && res.data && res.data.code === 200) {
							this.coupons = res.data.rows || []
							this.updateAvailableCoupons()
						} else {}
					},
					fail: (err) => {}
				})
			},
			// 选择优惠券
			selectCoupon(coupon) {
				if (this.selectedCoupon && this.selectedCoupon.id === coupon.id) {
					this.selectedCoupon = null
				} else {
					this.selectedCoupon = coupon
				}
			},
			// 更新可用优惠券列表
			updateAvailableCoupons() {
				if (!this.selectedServiceId) {
					this.availableCoupons = []
					this.selectedCoupon = null
					return
				}
				const selectedService = this.currentTechServices.find(s => s.id === this.selectedServiceId)
				if (!selectedService) {
					this.availableCoupons = []
					this.selectedCoupon = null
					return
				}
				// 筛选可用优惠券
				this.availableCoupons = this.coupons.filter(coupon => {
					// 检查优惠券是否过期
					const now = new Date()
					const dateString = coupon.coupons.validityEnd
					const [datePart, timePart] = dateString.split(' ')
					const [year, month, day] = datePart.split('-').map(Number)
					const [hours, minutes, seconds] = timePart.split(':').map(Number)
					const expireDate = new Date(year, month - 1, day, hours, minutes, seconds)
					if (now > expireDate) return false
					// 检查优惠券是否已使用
					if (coupon.coupons.status !== 1) return false
					// 检查优惠券是否适用于当前服务
					if (coupon.coupons && coupon.coupons.projectIds) {
						const projectIds = coupon.coupons.projectIds.split(',')
						if (!projectIds.includes(this.selectedServiceId.toString())) return false
					}
					// 检查订单金额是否满足优惠券使用条件
					if (coupon.coupons && coupon.coupons.minAmount && selectedService.price < coupon.coupons
						.minAmount) {
						return false
					}
					return true
				})
				// 如果当前选中的优惠券不可用，清除选择
				if (this.selectedCoupon && !this.availableCoupons.find(c => c.id === this.selectedCoupon.id)) {
					this.selectedCoupon = null
				}
			},
			// 加载用户会员卡
			loadMemberCards() {
				const userInfoStr = uni.getStorageSync('userInfo')
				let userInfo = null
				if (userInfoStr) {
					try {
						if (typeof userInfoStr === 'string') {
							const parsed = JSON.parse(userInfoStr)
							if (parsed.code === 200 && parsed.data) {
								userInfo = parsed.data
							} else {
								userInfo = parsed
							}
						} else {
							userInfo = userInfoStr
						}
					} catch (e) {
						userInfo = userInfoStr
					}
				}
				if (!userInfo || !userInfo.memberId) {
					return
				}
				uni.request({
					url: `${uni.$config.baseUrl}/usercard/usercard/listByUid`,
					method: 'GET',
					data: {
						memberId: userInfo.memberId
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data && res.data.code === 200) {
							this.memberCards = res.data.rows || []
							this.updateAvailableMemberCards()
						} else {}
					},
					fail: (err) => {}
				})
			},
			// 更新可用会员卡列表
			updateAvailableMemberCards() {
				if (!this.selectedServiceId) {
					this.availableMemberCards = []
					this.selectedMemberCard = null
					return
				}
				const selectedService = this.currentTechServices.find(s => s.id === this.selectedServiceId)
				if (!selectedService) {
					this.availableMemberCards = []
					this.selectedMemberCard = null
					return
				}
				// 筛选可用会员卡
				this.availableMemberCards = this.memberCards.filter(card => {
					// 检查会员卡是否有效
					if (card.status !== 1 || card.isDeleted === 1) return false
					// 储值卡检查剩余金额
					if (card.memberCard.cardType === 1 && card.balance < this.totalPrice)
						return false
					// 次卡检查剩余次数
					if (card.memberCard.cardType === 2 && card.remainingTimes <= 0)
						return false
					// 检查项目是否可用
					if (card.memberCard && card.memberCard.projectIds)
						return card.memberCard.projectIds.split(',').includes(this.selectedServiceId.toString())
					return false
				})
				// 如果当前选中的会员卡不可用，清除选择
				if (this.selectedMemberCard && !this.availableMemberCards.find(c => c.id === this.selectedMemberCard.id)) {
					this.selectedMemberCard = null
				}
			},
			// 选择会员卡
			selectMemberCard(card) {
				if (this.selectedMemberCard && this.selectedMemberCard.id === card.id) {
					this.selectedMemberCard = null;
					this.selectedCard = null;
					this.giftServices = [];
				} else {
					this.selectedMemberCard = card;
					this.selectedCard = card;
					if (card && card.cardId) {
						// 查询赠送项目列表
						request({
							url: `${uni.$config.baseUrl}/project/project/get-list-by-card-id`,
							method: 'GET',
							data: {
								cardId: card.cardId
							}
						}).then(res => {
							this.giftProject = {
								type: card.memberCard.cardType,
								balance: card.balance,
								status: card.giftProjectStatus,
								num: card.numberGiftItems,
								cardId: card.id,
								expireTime: card.memberCard.expireTime,
								list: res.data
							}
						})
					}
				}
				this.calculateTotalPrice();
			},
			// 获取当前登录用户的memberId
			getCurrentMemberId() {
				const userInfoStr = uni.getStorageSync('userInfo')
				let userInfo = null
				if (userInfoStr) {
					try {
						// 如果是字符串，尝试解析
						if (typeof userInfoStr === 'string') {
							const parsed = JSON.parse(userInfoStr)
							// 检查是否是登录响应格式
							if (parsed.code === 200 && parsed.data) {
								userInfo = parsed.data
							} else {
								userInfo = parsed
							}
						} else {
							// 如果不是字符串，直接使用
							userInfo = userInfoStr
						}
					} catch (e) {
						// 解析失败时，尝试直接使用
						userInfo = userInfoStr
					}
				}
				return userInfo ? userInfo.memberId : null
			},
			// 加载所有项目列表
			loadAllProjects() {
				uni.request({
					url: `${uni.$config.baseUrl}/project/project/listAll`,
					method: 'GET',
					data: {
						status: 1
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data && res.data.code === 200) {
							this.projectList = res.data.rows || []
						} else {}
					},
					fail: (err) => {}
				})
			},
			// 根据项目ID获取项目名称
			getProjectName(projectId) {
				const project = this.projectList.find(p => p.id === projectId)
				return project ? project.projectName : '未知项目'
			},
			// 计算总价（包含优惠券和会员卡）
			calculateTotalPrice() {
				let total = 0
				if (this.initPrice > 0) {
					console.log(this.initPrice)
					total += this.initPrice
				}
				// 添加主服务费用
				if (this.currentService && this.currentService.price) {
					total += Number(this.currentService.price) || 0
				}
				// 添加附加项目费用
				this.selectedAdditionalServices.forEach(serviceId => {
					const service = this.additionalServicesMap[serviceId]
					if (service && service.price) {
						total += Number(service.price) || 0
					}
				})
				// 应用优惠券
				if (this.selectedCoupon && this.selectedCoupon.coupons) {
					total = Math.max(0, total - (Number(this.selectedCoupon.coupons.amount) || 0))
				}
				// 如果选择了会员卡，只收取附加项目费用
				if (this.selectedMemberCard) {
					total = this.selectedAdditionalServices.reduce((sum, serviceId) => {
						const service = this.additionalServicesMap[serviceId]
						return sum + (service && service.price ? Number(service.price) : 0)
					}, 0)
				}
				this.calculatedTotalPrice = total
			},
			// 微信H5支付方法
			callWechatH5Pay(payData, orderId) {
				// 检查WeixinJSBridge是否准备就绪
				if (typeof WeixinJSBridge === 'undefined') {
					// WeixinJSBridge未定义，等待其加载
					if (typeof document !== 'undefined') {
						document.addEventListener('WeixinJSBridgeReady', () => {
							this.performWechatPay(payData, orderId);
						}, false);
					}
				} else {
					// WeixinJSBridge已存在，但仍需要确保其完全准备就绪
					if (typeof document !== 'undefined') {
						// 对于iOS系统，即使WeixinJSBridge存在，也建议等待Ready事件
						const isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
						if (isIOS) {
							document.addEventListener('WeixinJSBridgeReady', () => {
								this.performWechatPay(payData, orderId);
							}, false);
							// 设置超时，如果Ready事件没有触发，直接调用
							setTimeout(() => {
								this.performWechatPay(payData, orderId);
							}, 1000);
						} else {
							// 非iOS系统，直接调用
							this.performWechatPay(payData, orderId);
						}
					} else {
						// 非浏览器环境，直接调用
						this.performWechatPay(payData, orderId);
					}
				}
			},
			// 执行微信支付的具体方法
			performWechatPay(payData, orderId) {
				if (typeof WeixinJSBridge === 'undefined') {
					uni.showToast({
						title: '支付环境未准备好',
						icon: 'none'
					});
					this.isSubmitting = false;
					return;
				}
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						"appId": payData.appId,
						"timeStamp": payData.timeStamp,
						"nonceStr": payData.nonceStr,
						"package": payData.package,
						"signType": "RSA",
						"paySign": payData.paySign
					},
					(res) => {
						if (res.err_msg === "get_brand_wcpay_request:ok") {
							// 支付成功
							uni.showToast({
								title: '支付成功',
								icon: 'success',
								duration: 2000,
								success: () => {
									this.updateOrderPaymentStatus(orderId, 1)
									setTimeout(() => {
										uni.navigateTo({
											url: '/pages/my-orders/my-orders'
										})
									}, 2000)
								}
							});
						} else if (res.err_msg === "get_brand_wcpay_request:cancel") {
							// 用户取消支付
							uni.showToast({
								title: '支付已取消，可在全部订单中查看',
								icon: 'none'
							});
							this.isSubmitting = false;
						} else {
							// 支付失败
							uni.showToast({
								title: '支付失败',
								icon: 'none'
							});
							this.isSubmitting = false;
						}
					}
				);
			},
			// 更新订单支付状态
			updateOrderPaymentStatus(orderId, paymentStatus) {
				if (!orderId) {
					return
				}
				uni.request({
					url: `${uni.$config.baseUrl}/orders/orders/updatePaymentStatus`,
					method: 'POST',
					data: {
						orderId: orderId,
						paymentStatus: paymentStatus
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data.code === 200) {} else {}
					},
					fail: (err) => {}
				})
			},
			// 更新优惠券状态
			async updateCouponStatus(coupon) {
				try {
					const updateData = {
						id: coupon.id,
						status: 2, // 2-已使用
						useTime: new Date().toISOString()
					}
					const res = await uni.request({
						url: `${uni.$config.baseUrl}/usercoupons/usercoupons/update`,
						method: 'POST',
						data: updateData
					})
					if (res.statusCode === 200 && res.data.code === 200) {
						// 更新本地优惠券数据
						this.loadUserCoupons()
					}
				} catch (error) {}
			},
			// 选择礼品服务
			selectGiftService(gift) {
				if (this.selectedGiftId === gift.id) {
					this.selectedGiftId = null;
					this.selectedGift = null
				} else {
					this.selectedGiftId = gift.id;
					this.selectedGift = gift
				}
			},
			// 检查未选择的项目
			checkUnselectedItems() {
				this.showUnselectedTips = !(this.selectedStoreIndex !== null && this.selectedTechId &&
					this.selectedServiceId && this.selectedDate && this.selectedTime)
			},
			// 滚动到门店列表
			scrollToStore() {
				uni.pageScrollTo({
					selector: '.store-list',
				})
			},
			// 滚动到技师列表
			scrollToTechnician() {
				uni.pageScrollTo({
					selector: '.technician-section',
				})
			},
			// 滚动到服务项目
			scrollToService() {
				uni.pageScrollTo({
					selector: '.service-section',
				})
			},
			// 滚动到时间选择
			scrollToTime() {
				uni.pageScrollTo({
					selector: '.time-list',
				})
			},
			// 加载附加项目列表
			loadAdditionalServices() {
				uni.request({
					url: `${uni.$config.baseUrl}/project/project/listAll`,
					method: 'GET',
					data: {
						status: 1
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data && res.data.code === 200) {
							// 筛选出艾灸、刮痧、拔罐三个项目
							const targetServices = ['艾灸', '刮痧', '拔罐']
							this.additionalServiceList = res.data.rows.filter(project =>
								targetServices.includes(project.projectName)
							)
							// 创建项目映射
							this.additionalServiceList.forEach(service => {
								this.additionalServicesMap[service.id] = service
							})
						}
					}
				})
			},
			// 切换附加项目选择状态
			toggleAdditionalService(service) {
				const index = this.selectedAdditionalServices.indexOf(service.id)
				if (index === -1) {
					this.selectedAdditionalServices.push(service.id)
				} else {
					this.selectedAdditionalServices.splice(index, 1)
				}
				this.calculateTotalPrice() // 重新计算总价
			},
			checkUserRole() {
				const userInfoStr = uni.getStorageSync('userInfo')
				let userInfo = null
				if (userInfoStr) {
					try {
						if (typeof userInfoStr === 'string') {
							const parsed = JSON.parse(userInfoStr)
							if (parsed.code === 200 && parsed.data) userInfo = parsed.data
							else userInfo = parsed
						} else userInfo = userInfoStr
						if (userInfo && userInfo.role === 'technician') {
							this.isTechnician = true
							uni.showModal({
								title: '提示',
								content: '您当前登录的账号为技师账号，不可预约',
								showCancel: false,
								confirmText: '知道了'
							})
						}
					} catch (e) {}
				} else {
					console.info('没有用户信息')
				}
			},
		}
	}
</script>

<style lang="scss">
	.store-booking {
		min-height: 100vh;
		background: #F8F8F8;
		padding-bottom: 120rpx;

		// 导航栏样式
		.nav-bar {
			display: flex;
			align-items: center;
			height: 88rpx;
			background: #FFFFFF;
			padding: 0 30rpx;
			position: relative;

			.back-btn {
				width: 60rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				.back-icon {
					width: 40rpx;
					height: 40rpx;
					filter: brightness(0) invert(0);
					/* 恢复图标原始颜色 */
				}

				&:active {
					opacity: 0.8;
				}
			}

			.nav-title {
				flex: 1;
				text-align: center;
				font-size: 32rpx;
				font-weight: 500;
				color: #333;
				position: absolute;
				left: 0;
				right: 0;
				z-index: -1;
			}
		}

		.map-container {
			width: 100%;
			height: 500rpx;

			.store-map {
				width: 100%;
				height: 100%;
			}
		}

		.swipe-tip {
			display: block;
			text-align: right;
			font-size: 24rpx;
			color: #999;
			padding: 20rpx 30rpx 10rpx;
		}

		.store-list {
			margin-top: 20rpx;
			background: #FFFFFF;
			padding: 20rpx;
			white-space: nowrap;
			position: relative;
			scroll-behavior: smooth;

			.store-items {
				display: inline-flex;
				padding: 0 10rpx;
			}

			.store-item {
				display: flex;
				flex-direction: column;
				width: 300rpx;
				margin-right: 20rpx;
				padding: 20rpx;
				border-radius: 12rpx;
				background: #F8F8F8;
				transition: all 0.3s;

				&:last-child {
					margin-right: 10rpx;
				}

				&.active {
					background: rgba(43, 135, 255, 0.1);
				}

				.store-info {
					width: 100%;

					.store-image {
						width: 260rpx;
						height: 180rpx;
						border-radius: 12rpx;
						margin-bottom: 16rpx;
					}

					.store-name {
						font-size: 30rpx;
						color: #333;
						font-weight: 500;
						margin-bottom: 8rpx;
						display: block;
						white-space: normal;
					}

					.store-address {
						font-size: 24rpx;
						color: #666;
						display: block;
						white-space: normal;
						overflow: hidden;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
					}

					.store-phone {
						font-size: 24rpx;
						color: #666;
						margin-top: 8rpx;
						display: flex;
						align-items: center;
					}

					.phone-label {
						color: #999;
					}

					.phone-number {
						color: #007AFF;
					}
				}

				.select-btn {
					font-size: 26rpx;
					color: #2B87FF;
					padding: 8rpx 20rpx;
					border-radius: 24rpx;
					background: rgba(43, 135, 255, 0.1);
					margin-top: 12rpx;
					text-align: center;
				}

				&:active {
					opacity: 0.8;
				}
			}
		}

		.technician-section {
			margin-top: 20rpx;
			background: #FFFFFF;
			padding: 20rpx;

			.section-title {
				font-size: 32rpx;
				font-weight: 500;
				color: #333;
				padding: 0 10rpx 20rpx;
			}

			.technician-list {
				white-space: nowrap;

				.technician-items {
					display: inline-flex;
					padding: 0 10rpx;
				}

				.technician-item {
					width: 400rpx;
					margin-right: 20rpx;
					padding: 20rpx;
					background: #F8F8F8;
					border-radius: 12rpx;
					display: flex;
					align-items: center;
					transition: all 0.3s;

					&:last-child {
						margin-right: 10rpx;
					}

					&.active {
						background: rgba(43, 135, 255, 0.1);
					}

					.tech-avatar {
						width: 120rpx;
						height: 120rpx;
						border-radius: 60rpx;
						margin-right: 20rpx;
					}

					.tech-info {
						flex: 1;

						.tech-name {
							font-size: 30rpx;
							color: #333;
							font-weight: 500;
							margin-bottom: 8rpx;
							display: block;
						}

						.tech-tags {
							margin-bottom: 8rpx;

							.tag {
								font-size: 24rpx;
								color: #2B87FF;
								background: rgba(43, 135, 255, 0.1);
								padding: 4rpx 12rpx;
								border-radius: 20rpx;
								margin-right: 12rpx;
							}

							.exp {
								font-size: 24rpx;
								color: #666;
							}
						}

						.tech-rating {
							font-size: 24rpx;

							.score {
								color: #FF9500;
								margin-right: 12rpx;
							}

							.orders {
								color: #999;
							}
						}
					}

					&:active {
						opacity: 0.8;
					}
				}
			}
		}

		.service-section {
			margin-top: 20rpx;
			background: #FFFFFF;
			padding: 20rpx;

			.section-title {
				font-size: 32rpx;
				font-weight: 500;
				color: #333;
				padding: 0 10rpx 20rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.scroll-tip {
					font-size: 32rpx; // 从24rpx改为28rpx
					color: #2B87FF;
					opacity: 0.8;
				}
			}

			.service-list {
				padding: 0 20rpx;
				max-height: 600rpx;
				overflow-y: auto;

				.service-item {
					display: flex;
					padding: 20rpx;
					background: #FFFFFF;
					border-radius: 16rpx;
					margin-bottom: 20rpx;
					transition: all 0.3s;

					&.active {
						background: rgba(43, 135, 255, 0.05);
						border: 2rpx solid rgba(43, 135, 255, 0.3);
					}

					.service-image {
						width: 180rpx;
						height: 180rpx;
						border-radius: 12rpx;
						margin-right: 20rpx;
						flex-shrink: 0;
					}

					.service-content {
						flex: 1;
						display: flex;
						flex-direction: column;

						.service-header {
							display: flex;
							justify-content: space-between;
							align-items: center;
							margin-bottom: 12rpx;

							.service-name {
								font-size: 32rpx;
								color: #333;
								font-weight: 600;
							}

							.service-duration {
								display: flex;
								align-items: center;
								font-size: 24rpx;
								color: #666;
								background: #F5F5F5;
								padding: 4rpx 12rpx;
								border-radius: 20rpx;

								.icon {
									margin-right: 4rpx;
								}
							}
						}

						.service-desc {
							line-height: 1.6;
							margin-bottom: auto;
							display: -webkit-box;
							-webkit-line-clamp: 2;
							-webkit-box-orient: vertical;
							overflow: hidden;
						}

						.service-footer {
							display: flex;
							justify-content: space-between;
							align-items: center;
							margin-top: 16rpx;

							.price {
								display: flex;
								align-items: baseline;

								.symbol {
									font-size: 24rpx;
									color: #FF6B6B;
								}

								.number {
									font-size: 36rpx;
									color: #FF6B6B;
									font-weight: 600;
									margin-left: 4rpx;
								}
							}

							.select-status {
								font-size: 26rpx;
								color: #2B87FF;
								background: rgba(43, 135, 255, 0.1);
								padding: 6rpx 20rpx;
								border-radius: 24rpx;
							}
						}
					}

					&:active {
						transform: scale(0.98);
					}
				}
			}
		}

		.booking-form {
			margin-top: 20rpx;
			margin-bottom: 8%;
			background: #FFFFFF;
			padding: 0 30rpx;

			.form-item {
				padding: 30rpx 0;
				border-bottom: 1rpx solid #EEEEEE;

				&:last-child {
					border-bottom: none;
				}

				.label {
					font-size: 30rpx;
					color: #333;
					margin-bottom: 20rpx;
					display: block;
				}

				.time-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 20rpx;

					.label {
						font-size: 30rpx;
						color: #333;
						margin-bottom: 0;
					}

					.scroll-tip {
						font-size: 32rpx;
						color: #2B87FF;
						opacity: 0.8;
					}
				}

				.date-list {
					display: flex;
					justify-content: space-between;
					padding: 20rpx 0;

					.date-item {
						flex: 1;
						text-align: center;
						padding: 20rpx;
						border-radius: 12rpx;
						background: #F8F8F8;
						margin: 0 10rpx;
						transition: all 0.3s;
						min-width: 160rpx;

						&:first-child {
							margin-left: 0;
						}

						&:last-child {
							margin-right: 0;
						}

						&.active {
							background: rgba(43, 135, 255, 0.1);

							.day,
							.date {
								color: #2B87FF;
							}
						}

						.day {
							font-size: 28rpx;
							color: #333;
							margin-bottom: 8rpx;
							display: block;
						}

						.date {
							font-size: 24rpx;
							color: #666;
							display: block;
						}
					}
				}

				.time-list {
					display: flex;
					flex-wrap: wrap;
					padding: 10rpx 0;
					height: 400rpx;
					overflow-y: auto;

					.time-item {
						width: calc(33.33% - 20rpx);
						height: 90rpx;
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;
						text-align: center;
						padding: 10rpx 0;
						margin: 10rpx;
						border-radius: 12rpx;
						background: #F8F8F8;
						font-size: 28rpx;
						color: #333;
						transition: all 0.3s;

						&.active {
							background: rgba(43, 135, 255, 0.1);
							color: #2B87FF;
						}

						&.disabled {
							background: #F0F0F0;
							color: #999;
							pointer-events: none;
							text-decoration: line-through;

							.time-text {
								text-decoration: line-through;
							}

							.duration-text {
								text-decoration: line-through;
							}
						}

						.time-text {
							font-size: 28rpx;
							color: #333;
							margin-bottom: 4rpx;
						}

						.duration-text {
							font-size: 22rpx;
							color: #666;
							white-space: nowrap;
						}

						&.active {
							.time-text {
								color: #2B87FF;
							}

							.duration-text {
								color: #2B87FF;
							}
						}
					}

					&::-webkit-scrollbar {
						width: 4rpx;
					}

					&::-webkit-scrollbar-thumb {
						background-color: #ddd;
						border-radius: 4rpx;
					}
				}

				input {
					font-size: 30rpx;
					color: #333;
					width: 100%;

					&::placeholder {
						color: #999;
					}
				}

				textarea {
					width: 100%;
					height: 160rpx;
					font-size: 30rpx;
					color: #333;

					&::placeholder {
						color: #999;
					}
				}
			}
		}

		.coupon-section {
			.coupon-list {
				.coupon-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 30rpx;
					background: #F8F8F8;
					border-radius: 12rpx;
					margin-bottom: 20rpx;
					border: 2rpx solid transparent;
					transition: all 0.3s ease;

					&:last-child {
						margin-bottom: 0;
					}

					&.active {
						background: rgba(43, 135, 255, 0.05);
						border-color: #2B87FF;
					}

					.coupon-info {
						flex: 1;

						.coupon-name {
							font-size: 28rpx;
							color: #333;
							font-weight: 500;
							margin-bottom: 8rpx;
						}

						.coupon-desc {
							font-size: 24rpx;
							color: #666;
							margin-bottom: 8rpx;
						}

						.coupon-validity {
							font-size: 22rpx;
							color: #999;
						}
					}

					.coupon-amount {
						text-align: right;

						.amount {
							font-size: 36rpx;
							color: #FF6B35;
							font-weight: bold;
							display: block;
							margin-bottom: 8rpx;
						}

						.condition {
							font-size: 22rpx;
							color: #999;
						}
					}
				}

				.no-coupon {
					text-align: center;
					padding: 40rpx;
					color: #999;
					font-size: 28rpx;
				}
			}
		}

		.member-card-section {
			.member-card-list {
				.member-card-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 30rpx;
					background: #F8F8F8;
					border-radius: 12rpx;
					margin-bottom: 20rpx;
					border: 2rpx solid transparent;
					transition: all 0.3s ease;

					&:last-child {
						margin-bottom: 0;
					}

					&.active {
						background: rgba(43, 135, 255, 0.05);
						border-color: #2B87FF;
					}

					.card-info {
						flex: 1;

						.card-name {
							font-size: 28rpx;
							color: #333;
							font-weight: 500;
							margin-bottom: 8rpx;
						}

						.card-desc {
							font-size: 24rpx;
							color: #666;
							margin-bottom: 8rpx;
						}

						.card-validity {
							font-size: 22rpx;
							color: #999;
						}
					}

					.card-action {
						.action-text {
							font-size: 26rpx;
							color: #2B87FF;
							background: rgba(43, 135, 255, 0.1);
							padding: 8rpx 24rpx;
							border-radius: 24rpx;
						}
					}
				}

				.no-card {
					text-align: center;
					padding: 40rpx;
					color: #999;
					font-size: 28rpx;
				}
			}
		}

		.gift-service-list {
			background: #FFFFFF;
			padding: 40rpx;
			margin-top: 24rpx;

			.gift-item {
				padding: 30rpx;
				background: #F8F8F8;
				border-radius: 12rpx;
				margin-bottom: 20rpx;
				position: relative;
				transition: all 0.3s ease;

				&.active {
					background: rgba(43, 135, 255, 0.05);
					border: 2rpx solid #2B87FF;
				}

				&.disabled {
					opacity: 0.6;
					pointer-events: none;
				}

				.gift-info {
					display: flex;
					flex-direction: column;
					margin-bottom: 16rpx;

					.left-info {
						display: flex;
						align-items: center;
						margin-bottom: 12rpx;

						.name {
							font-size: 28rpx;
							color: #333;
							font-weight: 500;
							margin-right: 20rpx;
						}

						.times {
							font-size: 24rpx;
							color: #FF6B6B;
							font-weight: 500;

							&.times-disabled {
								color: #999;
							}
						}
					}

					.validity {
						font-size: 24rpx;
						color: #999;
					}
				}

				.action {
					position: absolute;
					right: 30rpx;
					top: 50%;
					transform: translateY(-50%);

					.action-text {
						font-size: 26rpx;
						color: #2B87FF;
						background: rgba(43, 135, 255, 0.1);
						padding: 8rpx 24rpx;
						border-radius: 24rpx;

						&.action-disabled {
							color: #999;
							background: #F0F0F0;
						}
					}
				}
			}
		}

		.unselected-tips {
			position: fixed;
			right: 30rpx;
			top: 120rpx;
			background: rgba(0, 0, 0, 0.7);
			padding: 20rpx;
			border-radius: 12rpx;
			z-index: 100;

			.tips-item {
				display: flex;
				align-items: center;
				padding: 12rpx 20rpx;
				font-size: 26rpx;
				color: #FFFFFF;
				white-space: nowrap;

				.icon {
					color: #FF6B35;
					margin-right: 12rpx;
					font-size: 24rpx;
				}

				.jump-text {
					margin-left: 20rpx;
					font-size: 24rpx;
					color: #2B87FF;
				}

				&:active {
					opacity: 0.8;
				}
			}
		}

		.submit-bar {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			height: 7%;
			background: #FFFFFF;
			display: flex;
			align-items: center;
			padding: 0 30rpx;
			box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

			.price-info {
				flex: 1;
				display: flex;
				align-items: baseline;

				.label {
					font-size: 28rpx;
					color: #333;
					margin-right: 8rpx;
				}

				.price {
					display: flex;
					align-items: baseline;

					.symbol {
						font-size: 24rpx;
						color: #FF6B6B;
					}

					.number {
						font-size: 36rpx;
						color: #FF6B6B;
						font-weight: 600;
						margin-left: 4rpx;
					}
				}
			}

			.submit-btn {
				width: 240rpx;
				height: 72rpx;
				line-height: 72rpx;
				background: #2B87FF;
				color: #FFFFFF;
				font-size: 28rpx;
				font-weight: 500;
				border-radius: 36rpx;
				text-align: center;
				margin-left: 20rpx;

				&:active {
					opacity: 0.9;
				}

				&[disabled] {
					background: #CCCCCC;
					opacity: 0.8;
					color: #FFFFFF;
				}
			}
		}

		.additional-services {
			background: #FFFFFF;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.service-options {
				display: flex;
				flex-wrap: wrap;
				gap: 20rpx;
				margin-top: 20rpx;

				.service-option {
					flex: 1;
					min-width: 200rpx;
					padding: 20rpx;
					background: #F8F8F8;
					border-radius: 12rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					border: 2rpx solid transparent;
					transition: all 0.3s ease;

					.service-name {
						font-size: 28rpx;
						color: #333;
						margin-bottom: 8rpx;
					}

					.service-price {
						font-size: 24rpx;
						color: #666;
					}

					&.active {
						background: rgba(43, 135, 255, 0.05);
						border-color: #2B87FF;

						.service-name {
							color: #2B87FF;
						}

						.service-price {
							color: #2B87FF;
						}
					}

					&:active {
						transform: scale(0.98);
						opacity: 0.9;
					}
				}
			}
		}

		.remark-section {
			margin-top: 20rpx;
			background: #FFFFFF;
			padding: 20rpx;

			.label {
				font-size: 30rpx;
				color: #333;
				margin-bottom: 20rpx;
				display: block;
			}

			textarea {
				width: 100%;
				height: 160rpx;
				font-size: 30rpx;
				color: #333;

				&::placeholder {
					color: #999;
				}
			}
		}
	}
</style>